/**
 * 待完成功能：重新生成时，考虑旧的写的功能不被覆盖，最大可能帮用户更新
 * @constructor
 */
function McNewVxeTableConfig(){
  this.projectUuid = MagicalCoder.getUrlParameter("projectUuid");
  this.SIMPLE_TABLE_HTML =
    '\t<mc-new-vxe-table :data.sync="tableList" mc-version="v2"  class="mc-bg-transparent mc-scroll-y-hidden" :auto-resize="true" height="600"  mc-query-url=""  mc-query-method="post" :mc-show-checkbox="false" :mc-show-pagination="false" :mc-scroll-enable="true" :mc-scroll-speed="100">\n' +
    '\t</mc-new-vxe-table>';
  this.TABLE_HTML=
    '<mc-new-vxe-table :mc-top-toolbar="false" :mc-dialog-footer-btn="false" :data.sync="tableList" mc-version="v2" :auto-resize="true" height="600" :mc-page-size="10" mc-query-url="magical_lowcode/openapi/crud/magical_coder_manage_admin_user/page" mc-save-url="magical_lowcode/openapi/crud/xxx/save" mc-delete-url="magical_lowcode/openapi/crud/xxx/delete-by-pk" mc-query-method="post" :mc-open-pane="{\'type\':\'drawer\',\'width\':\'70%\'}">\n' +
    '<template #query-left="scope"></template>' +
    '<template #query="scope"></template>' +
    '<template #operate="scope"></template>\n' +
    '<template #form="scope">' +
    '\t<el-form class="mc-vxe-table-form" mcstyle="ab-unit-top:px;ab-unit-height:px" label-width="100px" size="small" :model="scope.row"></el-form>\n' +
    '</template>\n' +
    '<template #dialog-footer="scope"></template>\n' +
    '<template #parent="scope"></template>\n' +
    '</mc-new-vxe-table>';
}

McNewVxeTableConfig.prototype.chooseTable=function () {
  var projectUuid = this.projectUuid;
  var config = {type:"html",
    callback:{
      htmlCallback:function(param){
        var htmlTemp = '<div class="layui-row layui-col-space3 parent-child-wp" id="mcDbTableApp">'+
          '<div class="layui-col-xs3 mc-change-attr__now">选择表</div>'+
          '<div class="layui-col-xs9">'+
          '<el-tag effect="plain" @click="openDrawer(\'parent\')">主表配置</el-tag>'+
          '<el-tag style="margin-left: 10px" effect="plain" @click="openDrawer(\'child\')">新增内部布局子表</el-tag>'+
          '<mc-drawer @closed="closeDrawer" style="overflow-y:scroll" title="选择表" :visible.sync="drawer" direction="rtl" :modal="false" size="300px">'+
            '<div><span style="margin-right: 10px">新增字段</span><el-radio-group @input="changeRadioGroup" v-model="tableMergeType"><el-radio label="merge">智能合并</el-radio><el-radio label="replace">替换最新</el-radio></el-radio-group></div>'+
            '<div><span style="margin-right: 10px">表格操作</span><el-radio-group @input="changeRadioGroup" v-model="tableOperate"><el-radio label="read">只 读&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-radio><el-radio label="edit">可编辑</el-radio></el-radio-group></div>'+
            '<div><span style="margin-right: 10px">保存方式</span><el-radio-group @input="changeRadioGroup" v-model="tableSave"><el-radio label="db">立即入库</el-radio><el-radio label="batch">批量入库</el-radio></el-radio-group></div>'+
            '<div><span style="margin-right: 10px">布局方式</span><el-radio-group @input="changeRadioGroup" v-model="tableLayout"><el-radio label="tb">上下布局</el-radio><el-radio label="lr">左树右表</el-radio></el-radio-group></div>'+
            '<div><span style="margin-right: 10px">按钮位置</span><el-radio-group @input="changeRadioGroup" v-model="mcTopToolbar"><el-radio :label="false">默认</el-radio><el-radio :label="true">顶部</el-radio></el-radio-group></div>'+
            '<div><span style="margin-right: 10px">栅格布局</span><el-radio-group @input="changeRadioGroup" v-model="mcGrid"><el-radio :label="false">默认</el-radio><el-radio :label="true">栅格</el-radio></el-radio-group><el-input size="mini" style="margin-left:10px;width: 50px" v-if="mcGrid" v-model="gridSpan"></el-input></div>'+
            '<el-checkbox v-if="operate==\'child\'" v-model="cascadeDelete">父表级联删除</el-checkbox>'+
            '<el-tree  node-key="uuid" ref="selectTree" :data="treeList" default-expand-all @node-click="handleNodeClick" :props="defaultProps"><span :uuid="scope.data.uuid" class="slot-t-node" slot-scope="scope" style="width:100%">{{scope.data.name}}</span></el-tree>'+
            '<div style="display:none;margin-top:4px;font-size: large">强转返回逗号分隔字段为数组</div>' +
            '<el-form style="display:none;" label-position="left">'+
            '<el-form-item><el-checkbox-group v-model="arrayFields"><el-checkbox :label="item.name" v-for="(item,key) in javaFields" :key="item.name">{{item.comment}}</el-checkbox></el-checkbox-group></el-form-item>'+
            '</el-form>' +
            '<template #footer class="dialog-footer"><el-button size="small" @click="closeDrawer">取消</el-button><el-button size="small" type="primary" @click="submitForm()">确定</el-button></template>'+
          '</mc-drawer>'+
          '</div>'+
          '</div>';
        return htmlTemp;
      },
      render:function (param) {
        //从magicalCoder获取当前聚焦节点的属性值 准备传入vue里
        var config = param.config,focusNode=param.focusNode;
        var mcArrayFields = focusNode.attributes[':mc-array-fields'];
        if(mcArrayFields){
          mcArrayFields = JSON.parse(mcArrayFields.replace(/'/g,'"'));
        }else{
          mcArrayFields = [];
        }
        new Vue({
          el: '#mcDbTableApp',
          data: {
            operate:"parent",//parent child 操作的表类型
            treeList:[],
            defaultProps: {
              children: 'children',
              label: 'name',
            },
            drawer : false,
            javaFields:[],
            arrayFields:mcArrayFields,
            //生成表操作方式
            tableOperate:"read",//edit
            //立即入库
            tableSave:"db",//batch
            //表格布局
            tableLayout:"tb",//lr
            //新表合并方式 merge合并 replace替换最新
            tableMergeType:"merge",
            // 是否顶部按钮
            mcTopToolbar:false,
            // 是否开启表单栅格布局
            mcGrid:false,
            // 24 默认为8，三列，6 四列，12 两列
            gridSpan:8,
            attributes:{},
            html:"",
            tableInfo:{},//catalog schema table pidName
            parentInfo:null,//catalog schema table pk:{name}
            cascadeDelete:true
          },
          mounted:function(){

          },
          methods:{
            //重置下选中表
            changeRadioGroup:function () {
              this.$refs['selectTree'].setCurrentKey(null);
              this.tableInfo={};
            },
            openDrawer:function(operate){
              this.operate = operate;
              if(operate=='parent'){
                this.tableSave='db';
                this.tableOperate='read';
              }else if(operate=='child'){
                this.tableSave='batch';
                this.tableOperate='edit';
              }
              this.drawer = true;
              var _t = this;
              CommonUtil.axiosWithServerName("get","/magical_lowcode/user/database/list",
                {
                  params: {projectUuid:projectUuid}
                },function(response){
                  _t.treeList = response.data;
                }
              )
            },
            closeDrawer:function(){
              if(this.arrayFields){
                MAGICAL_CODER_API.changeAttr({node:focusNode,name:":mc-array-fields",value:JSON.stringify(this.arrayFields).replace(/"/g,"'"),triggerChange:true})
              }else{

              }
              MAGICAL_CODER_API.refreshRightAttrPane({id:focusNode.magicalCoder.id})
              //
            },
            handleNodeClick:function(data,node){
              if(node.level==1){
                this.tableInfo={};//还原下
                return;//数据库不用管
              }
              var databaseUuid = '';
              var database = null;
              for(var i=0;i<this.treeList.length;i++){
                var children = this.treeList[i].children;
                if(children){
                  for(var j=0;j<children.length;j++){
                    if(children[j].uuid == data.uuid){
                      databaseUuid=this.treeList[i].uuid;
                      database = this.treeList[i];
                      break;
                    }
                  }
                }
              }
              this.parentInfo = this.getTableInfo(focusNode);

              var suffix = CommonUtil.KCVUtil.buildCatalogShemaUrl(database);
              var tableName = data.name;
              this.tableInfo.catalog = database.catalog;
              this.tableInfo.schema = database.schema;
              this.tableInfo.table=tableName;//pidName怎么找
              var _t = this;
              CommonUtil.axiosWithServerName("get","/magical_lowcode/user/table/info",
                {
                  params: {
                    projectUuid:projectUuid,
                    databaseUuid:databaseUuid,
                    uuid:data.uuid,
                  }
                },function(response) {
                    var childrenHtml = _t.upDownChildrenHtml(focusNode);
                    var html = response.data.data.html;
                    var rootNode= MAGICAL_CODER_API.htmlToRootNode({html:html,pure:true});
                    _t.chooseTable(childrenHtml,rootNode,tableName,suffix);
                })

            },
            //判断这个节点是哪个表
            getTableInfo:function (focusNode) {
              var html2Coder = new Html2Coder();
              return html2Coder.parseTableInfo(focusNode.attributes['mc-query-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/page$/gi)||
              html2Coder.parseTableInfo(focusNode.attributes['mc-save-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/save$/gi)||
              html2Coder.parseTableInfo(focusNode.attributes['mc-delete-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/delete-by-pk$/gi)||
              html2Coder.parseTableInfo(focusNode.attributes['mc-update-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/update$/gi)||
              html2Coder.parseTableInfo(focusNode.attributes['mc-export-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/export-excel$/gi)||
              html2Coder.parseTableInfo(focusNode.attributes['mc-query-url'],/^magical_lowcode\/openapi\/crud\/(.*)\/page$/gi)
            },
            chooseTable:function (childrenHtml,rootNode,tableName,suffix) {
              var _t = this;
              var html2Coder = new Html2Coder();
              var javaClassName = html2Coder.tableNameToClassName(tableName);
              //填充预定的后端接口
              this.attributes['mc-query-url'] = "magical_lowcode/openapi/crud/"+tableName+"/page"+suffix ;
              this.attributes['mc-save-url'] = "magical_lowcode/openapi/crud/"+tableName+"/save"+suffix ;
              this.attributes['mc-update-url'] = "magical_lowcode/openapi/crud/"+tableName+"/update"+suffix ;
              this.attributes['mc-delete-url'] = "magical_lowcode/openapi/crud/"+tableName+"/delete-by-pk"+suffix ;
              this.attributes['mc-export-url'] = "magical_lowcode/openapi/crud/"+tableName+"/export-excel"+suffix ;
              this.attributes['mc-query-method'] = "post" ;
              this.attributes['mc-layout']=_t.tableLayout;
              this.attributes['mc-top-toolbar']=_t.mcTopToolbar;
              if(this.operate=='child'){
                  this.attributes[':data.sync']="scope.row.saveList"+javaClassName;
                  this.attributes[':api-delete-data.sync']="scope.row.deleteList"+javaClassName;
              }
              // rootNode = eval("("+rootNode+")");
              var tableInfo = _t.tableFields(rootNode);
              //表信息
              var tableObj = html2Coder.nodeToTableDdl(rootNode);
              _t.javaFields = tableInfo.fields;
              if(this.operate=='child'){
                _t.fitPidName(tableObj.fields)
              }
              if(_t.javaFields){
                var fieldMap = {}
                for(var i=0;i<_t.javaFields.length;i++){
                  var jf = _t.javaFields[i];
                  fieldMap[jf.name] = true;
                }
                for(var j=0;j<_t.arrayFields.length;j++){
                  var key = _t.arrayFields[j];
                  var v = fieldMap[key]
                  if(!v){
                    _t.javaFields.push({name:key,comment:key})
                  }
                }
              }
              this.html = _t.mergeHtml(childrenHtml,tableObj,rootNode,tableName,suffix);

            },
            fitPidName:function (javaFields) {
              if(this.parentInfo){
                if(javaFields){
                  for(var i=0;i<javaFields.length;i++){
                    var field = javaFields[i];
                    var fk = field.fk;
                    if(fk){
                      if(this.parentInfo.schema==fk.schema && this.parentInfo.catalog == fk.catalog && this.parentInfo.table == fk.table){
                        this.tableInfo.pidName = field.name;
                        this.parentInfo.pk = fk.pk;
                        break
                      }
                    }
                  }
                }
              }
            },
            mergeHtml:function (childrenHtml,tableObj,rootNode,tableName,suffix) {
              var _t = this;
              var copyRootNode = CommonUtil.KCVUtil.cloneDeep(rootNode);
              var copy2RootNode = CommonUtil.KCVUtil.cloneDeep(rootNode);
              var rootNodeCp = CommonUtil.KCVUtil.cloneDeep(rootNode);

              var tableColumnHtml = "";
              if(_t.tableOperate=='edit'){
                tableColumnHtml= _t.buildEditColumnHtml(copyRootNode,tableObj);
              }else{
                tableColumnHtml= _t.buildColumnHtml(rootNode,tableObj);
              }
              var pk = tableObj.pk||{name:""}
              //表单编辑区域
              _t.setVmodel(rootNode,'scope.row.',false);
              var editFormHtml = this.buildEditFormHtml(rootNode);
              //查询区域
              _t.setVmodel(rootNodeCp,'scope.row.',true);
              var vifPkHtml=this.vIfParentPkNotNullHtml();
              var queryFormHtml= this.buildQueryHtml(rootNodeCp,vifPkHtml,pk);
              //左侧查询 树节点
              var result =_t.setVmodel(copy2RootNode,'scope.row.',true,true);
              var leftTreeQuery = this.buildLeftQueryHtml(result,vifPkHtml);
              var insertDataParam = leftTreeQuery.insertDataParam;
              var leftTreeQueryHtml = leftTreeQuery.html;
              var buildDialogToolHtml = this.buildDialogToolHtml();
              var buildTableToolbarHtml = this.buildTableToolbarHtml(pk,vifPkHtml,insertDataParam,tableName,suffix);
              //TODO 最常修改
              var htmlstr=
                '<template #query-left="scope">'+leftTreeQueryHtml+'</template>'+
                '<template #query="scope">'+queryFormHtml+'</template>'+
                '<template #operate="scope">'+buildTableToolbarHtml+'</template>'+
                tableColumnHtml+
                '<template #form="scope">'+editFormHtml+'</template>'+
                '<template #dialog-footer="scope">' +buildDialogToolHtml+'</template>'+
                childrenHtml;
                return htmlstr;
            },
            upDownChildrenHtml:function (focusNode) {
              var childrenHtml = "";
                var children = focusNode.magicalCoder.children;
                for(var i=0;i<children.length;i++){
                  var child = children[i];
                  var slotParent = child.attributes['#parent'];
                  if(slotParent){//找到了 加个lazy有利于内部空间宽自适应
                    childrenHtml = MAGICAL_CODER_API.nodeToHtml({node:child,pure:true});
                    break;
                  }
                }
                return childrenHtml;
            },
            getPidName:function () {
              if(this.tableInfo){
                return this.tableInfo.pidName;
              }
              return null;
            },
            setVmodel:function(rootNode, value,fromQuery,onlyNeedTree){
              var result = {treeNodes:[]};
              rootNode.attributes['id']='';
              rootNode.attributes['size']='small';
              rootNode.attributes['class']=""

              if(fromQuery){
                rootNode.attributes[':inline']="true";
              }else{
                rootNode.attributes[':model']="scope.row";
              }
              var children = rootNode.magicalCoder.children;
              if(children){
                for(var i=0;i<children.length;i++){
                  var elFormItem = children[i];
                  var label = elFormItem.attributes['label'];
                  var attributes= elFormItem.attributes;
                  var magicalCoder = elFormItem.magicalCoder;
                  // if(fromQuery){
                  attributes['style']='';
                  // }
                  var rules = attributes[':rules'];
                  var prop = attributes['prop'];
                  var required = attributes['required'];
                  if(required){
                    if(!rules){
                      rules = "[{required:true,message:'必填项'}]";
                      attributes[':rules']=rules;
                    }
                  }
                  {//寻找包含的控件
                    if(magicalCoder.children){
                      var controlNode = magicalCoder.children[0]
                      var controlAttributes = controlNode.attributes;
                      var controlMagicalCoder = controlNode.magicalCoder;
                      var tagName = controlMagicalCoder.tagName;
                      var vModel = controlAttributes['v-model'];
                      if(vModel){
                        controlAttributes['v-model']=value+''+vModel;
                      }
                      //后续其他组件双向绑定就用这个变量名
                      var dataSync = controlAttributes[':data.sync'];
                      if(dataSync){
                        controlAttributes[':data.sync']=value+''+dataSync;
                      }
                      if(rules &&!prop){
                        attributes['prop']=vModel||dataSync;
                      }
                      if(fromQuery){
                        attributes['required']="";
                        attributes['prop']="";
                        attributes[':rules']="";
                        if(onlyNeedTree){//只要树节点的
                          if(tagName=='mc-tree'){
                            controlAttributes[':mc-pop-tree']=false;//
                            controlAttributes['@mc-node-click']='scope.vue.reload()';//
                            var fieldName = vModel||dataSync;
                            result.treeNodes.push({info:{field:fieldName,label:label},node:controlNode});
                            continue;
                          }
                        }else {
                          //左树右表
                          if(this.tableLayout=='lr'){
                            if(tagName=='mc-tree'){
                              children.splice(i,1);
                              i--;
                              continue;
                            }
                          }
                        }

                        if(tagName=='el-slider'){
                          controlMagicalCoder.tagName = 'el-input';
                        }else if(tagName == 'mc-switch' ||tagName == 'mc-image-net-upload'||tagName == 'mc-image-upload' || tagName=='mc-kindeditor'){//此类组件无需查询
                          children.splice(i,1);
                          i--;
                        }else if(tagName=='mc-switch'){
                          controlAttributes[':mc-allow-null']="true";
                          controlAttributes[':mc-default-value']="";
                        }/*else if(tagName=='mc-remote-select' && controlAttributes['multiple']){//多选外键
                          controlAttributes['mc-condition']="like";
                        }*/
                      }
                      //兼容下父子下拉框
                      if(tagName=='mc-parent-child-select'){
                        var pmodel = controlAttributes[':p-model.sync'];
                        if(pmodel){
                          controlAttributes[':p-model.sync']=value+''+pmodel;
                        }
                      }else if(tagName == 'mc-parent-child-grandson-select'){
                        var pmodel = controlAttributes[':p-model.sync'];
                        if(pmodel){
                          controlAttributes[':p-model.sync']=value+''+pmodel;
                        }
                        var cmodel = controlAttributes[':c-model.sync'];
                        if(cmodel){
                          controlAttributes[':c-model.sync']=value+''+cmodel;
                        }
                      }
                    }
                  }

                }
              }
              return result;
            },
            //寻找表格下的列
            getMcVxeTableColumns:function (tableNode) {
              if(tableNode==null){
                return {columns:[],operateColumns:[]};
              }
              var columns = [];
              var operateColumns = [];
              var children = tableNode.magicalCoder.children;
              if(children){
                for(var i=0;i<children.length;i++){
                  var child = children[i];
                  if(child.magicalCoder.identifier=='mc-new-vxe-table-column'){
                    if(child.attributes.title!=='操作'){//普通字段
                      columns.push(child);
                    }else {//操作字段
                      operateColumns.push(child)
                    }
                  }
                }
              }
              return {columns:columns,operateColumns:operateColumns};
            },
            getMcVxeTableColumnMap:function (columns) {
              var oldTableColumnMap = {};
              if(columns){
                for(var i=0;i<columns.length;i++){
                  var child = columns[i];
                  if(child.attributes.field){
                    oldTableColumnMap[child.attributes.field]=child;
                  }
                }
              }
              return oldTableColumnMap;
            },
            getOperateFocusNode:function () {
              if(this.operate=='parent'){
                return focusNode;
              }
              return null;
            },
            getOperateFocusNodeChildren:function () {
              var node = this.getOperateFocusNode();
              if(node){
                return node.magicalCoder.children;
              }
              return null;
            },
            /**获取列*/
            buildColumnHtml:function(rootNode,tableObj){
              var columnHtml = [];

              var oldMcVxeTableColumns = this.getMcVxeTableColumns(this.getOperateFocusNode());
              var oldTableColumnMap = this.getMcVxeTableColumnMap(oldMcVxeTableColumns.columns);
              var oldColumnHtml = MAGICAL_CODER_API.nodesToHtml({nodes:oldMcVxeTableColumns.columns,pure:true})
              var oldColumnOperateHtml = MAGICAL_CODER_API.nodesToHtml({nodes:oldMcVxeTableColumns.operateColumns,pure:true})
              if(oldMcVxeTableColumns.operateColumns.length<=0){
                oldColumnOperateHtml = this.buildOperateHtml(tableObj);
              }
              if(!this.isMergeNewField()){//使用全选的列表字段
                oldMcVxeTableColumns={columns:[],operateColumns:[]};
                oldTableColumnMap={};
                oldColumnHtml="";
                oldColumnOperateHtml=this.buildOperateHtml(tableObj);
              }
              //字段信息
              var pidName = this.getPidName();
              var children = rootNode.magicalCoder.children;
              if(children){
                var addColWidth = children.length>8;
                for(var i=0;i<children.length;i++){
                  var field = {};
                  var elFormItem = children[i];
                  var attributes = elFormItem.attributes;
                  var magicalCoder = elFormItem.magicalCoder;
                  //注释
                  field.comment = attributes.label;
                  var mcColConfig = "";

                  {//寻找包含的控件
                    if(magicalCoder.children){
                      var controlNode = magicalCoder.children[0]
                      var controlAttributes = controlNode.attributes;
                      var controlMagicalCoder = controlNode.magicalCoder;
                      var tagName = controlMagicalCoder.tagName;
                      if(tagName=='mc-kindeditor'){
                        //这些组件就忽略展示列
                        continue;
                      }
                      var vModel = controlAttributes['v-model'];
                      field.name = vModel;
                      if(!vModel){
                        field.name = controlAttributes[':data.sync'];
                      }
                      if(tagName=='mc-parent-child-select'){//父子下拉框
                        mcColConfig = this.parsePCSConfig(controlNode.attributes[':mc-child-config'])
                        //检测父亲下拉框是否配置字段
                        var pmodel = controlAttributes[':p-model.sync'];
                        if(pmodel){
                          field.comment = controlAttributes['mc-child-comment']||vModel;
                          if(!oldTableColumnMap[pmodel]){//存在就不追加了
                            columnHtml.push('<mc-new-vxe-table-column'+this.parsePCSConfig(controlNode.attributes[':mc-parent-config'])+ this.calcColWidth(field.comment,addColWidth)+' field="'+pmodel+'" title="'+(controlAttributes['mc-parent-comment']||pmodel)+'"></mc-new-vxe-table-column>');
                          }
                        }
                      }else if(tagName=='mc-parent-child-grandson-select'){
                        mcColConfig = this.parsePCSConfig(controlNode.attributes[':mc-grandson-config'])
                        //检测父亲下拉框是否配置字段
                        var pmodel = controlAttributes[':p-model.sync'];
                        if(pmodel&&!oldTableColumnMap[pmodel]){
                          columnHtml.push('<mc-new-vxe-table-column'+this.parsePCSConfig(controlNode.attributes[':mc-parent-config'])+ this.calcColWidth(field.comment,addColWidth)+' field="'+pmodel+'" title="'+(controlAttributes['mc-parent-comment']||pmodel)+'"></mc-new-vxe-table-column>');
                        }
                        //检测父亲下拉框是否配置字段
                        var cmodel = controlAttributes[':c-model.sync'];
                        if(cmodel&&!oldTableColumnMap[cmodel]){
                          field.comment = controlAttributes['mc-grandson-comment']||vModel;
                          columnHtml.push('<mc-new-vxe-table-column'+this.parsePCSConfig(controlNode.attributes[':mc-child-config'])+ this.calcColWidth(field.comment,addColWidth)+' field="'+cmodel+'" title="'+(controlAttributes['mc-child-comment']||cmodel)+'"></mc-new-vxe-table-column>');
                        }
                      }else if(tagName=='mc-image-upload'){//图片
                        var colHtml =
                          '<mc-new-vxe-table-column title="'+field.comment+'" :mc-tmp-data="{\'stage\':\'db\',\'apiUuid\':\'\',\'tableUuid\':\'\'}" :mc-col-config="{\'type\':\'user\',\'options\':[],\'api\':{\'method\':\'post\',\'url\':\'\',\'params\':[],\'fields\':[]}}"'+ this.calcColWidth(field.comment,addColWidth)+'>'+
                          '<template #row="scope"><div class="mc-div-pane"><mc-image :src="scope.row.'+field.name+'"></mc-image></div></template>'+
                          '</mc-new-vxe-table-column>';
                        if(!oldTableColumnMap[field.name]){
                          columnHtml.push(colHtml);
                        }
                        continue;
                      }else if(tagName=='mc-image-net-upload'){//图片缺个mc-image-net-图片
                        /* var colHtml =
                          '<mc-new-vxe-table-column title="'+field.comment+'" :mc-tmp-data="{\'stage\':\'db\',\'apiUuid\':\'\',\'tableUuid\':\'\'}" :mc-col-config="{\'type\':\'user\',\'options\':[],\'api\':{\'method\':\'post\',\'url\':\'\',\'params\':[],\'fields\':[]}}">'+
                          '<template #row="scope"><div class="mc-div-pane"><mc-image :src="scope.row.'+field.name+'"></mc-image></div></template>'+
                          '</mc-new-vxe-table-column>';
                        columnHtml.push(colHtml);
                        continue; */
                      }else if(tagName=='mc-remote-select' && controlAttributes['multiple']){//多选外键
                        mcColConfig = CommonUtil.KCVUtil.findMcRemoteSelectConfig(controlNode)
                        var remCol = '<mc-new-vxe-table-column title="'+field.comment+'" :mc-col-config="{\'type\':\'user\'}"  :mc-sortable="true"'+ this.calcColWidth(controlNode,addColWidth)+'>\n' +
                          '<template #row="scope">\n' +
                          '  <div class="mc-div-pane">\n' +
                          '    <mc-remote-select v-model="scope.row.'+vModel+'" @focus="focus" '+mcColConfig+' multiple disabled></mc-remote-select>\n' +
                          '  </div>\n' +
                          '</template>\n' +
                          '</mc-new-vxe-table-column>';
                        if(!oldTableColumnMap[field.name]){
                          columnHtml.push(remCol);
                        }
                        continue;
                      }
                      else{
                        //构建mc-col-config
                        mcColConfig = this.buildColConfigHtml(controlNode);
                      }
                    }
                  }
                  if(field.name!==pidName&&!oldTableColumnMap[field.name]){
                    columnHtml.push('<mc-new-vxe-table-column'+mcColConfig+' field="'+field.name+'" title="'+field.comment+'" :mc-sortable="true" '+ this.calcColWidth(field.comment,addColWidth)+'></mc-new-vxe-table-column>');
                  }
                }
              }
              return oldColumnHtml + columnHtml.join("")+oldColumnOperateHtml;
            },
            //是否合并新字段
            isMergeNewField:function () {
              return this.tableMergeType==='merge';
            },
            calcColWidth:function (label,addColWidth) {
                if(!addColWidth){
                  return "";
                }
                if(!label){
                  return " width='200px' ";
                }
                return " width='"+(label.length*50)+"px' ";
            },
            //生成可编辑的列
            buildEditColumnHtml:function(rootNode,tableObj){
              var pk = tableObj.pk;
              var columnHtml = [];
              //{columns:,operateColumns:}
              var oldMcVxeTableColumns = this.getMcVxeTableColumns(this.getOperateFocusNode());
              var oldTableColumnMap = this.getMcVxeTableColumnMap(oldMcVxeTableColumns.columns);
              var oldColumnHtml = MAGICAL_CODER_API.nodesToHtml({nodes:oldMcVxeTableColumns.columns,pure:true})
              var oldColumnOperateHtml = MAGICAL_CODER_API.nodesToHtml({nodes:oldMcVxeTableColumns.operateColumns,pure:true})
              if(oldMcVxeTableColumns.operateColumns.length<=0){
                oldColumnOperateHtml = this.buildOperateHtml(tableObj);
              }
              if(!this.isMergeNewField()){//使用全选的列表字段
                oldMcVxeTableColumns={columns:[],operateColumns:[]};
                oldTableColumnMap={};
                oldColumnHtml="";
                oldColumnOperateHtml=this.buildOperateHtml(tableObj);
              }
              //深拷贝一下
              var pidName = this.getPidName();
              //字段信息
              var children = rootNode.magicalCoder.children;
              if(children){
                var addColWidth = children.length>8;
                for(var i=0;i<children.length;i++){
                  var field = {};
                  var elFormItem = children[i];
                  var attributes = elFormItem.attributes;
                  var magicalCoder = elFormItem.magicalCoder;
                  //注释
                  field.comment = attributes.label;

                  {//寻找包含的控件
                    if(magicalCoder.children){
                      var controlNode = magicalCoder.children[0]
                      var controlAttributes = controlNode.attributes;
                      var controlMagicalCoder = controlNode.magicalCoder;
                      var tagName = controlMagicalCoder.tagName;
                      if(tagName=='mc-kindeditor'){
                        //这些组件就忽略展示列
                        continue;
                      }
                      var vModel = controlAttributes['v-model'];
                      field.name = vModel;
                      if(!vModel){
                        field.name = controlAttributes[':data.sync'];
                        controlAttributes[':data.sync']="scope.row."+field.name;
                      }else{
                        controlAttributes['v-model']="scope.row."+field.name;
                      }
                      controlAttributes['size']="mini";
                      if(this.tableSave=='db'){//事件处理要更新库
                        var vBindChange="scope.vue.dbUpdate({confirm:true,data:{"+pk.name+":scope.row."+pk.name+","+field.name+":scope.row."+field.name+"},callback:function(res){scope.vue.reload({current:true})}})";
                        var changeMethod = "@change";
                        switch(tagName){
                          case 'mc-remote-select':
                          case 'mc-tree':
                            changeMethod = "@mc-change";
                            break;
                        }
                        controlAttributes[changeMethod]=vBindChange;
                      }
                      //转成html field用于排序
                      var controlHtml = MAGICAL_CODER_API.nodeToHtml({node:controlNode,pure:true});
                      var remCol = '<mc-new-vxe-table-column title="'+field.comment+'" field="'+field.name+'" :mc-col-config="{\'type\':\'user\'}"  :mc-sortable="true" '+this.calcColWidth(field.comment,addColWidth)+'>\n' +
                        '<template #row="scope">\n' +
                        '  <div class="mc-div-pane">\n' +
                        controlHtml +
                        '  </div>\n' +
                        '</template>\n' +
                        '</mc-new-vxe-table-column>';
                      if(field.name!==pidName && !oldTableColumnMap[field.name]){//存在就不追加了){
                        columnHtml.push(remCol);
                      }
                    }
                  }
                }
              }
              return oldColumnHtml+columnHtml.join("")+oldColumnOperateHtml;
            },
            buildOperateHtml:function (tableObj) {
              var pk = tableObj.pk||{name:""}
              var _t = this;
              var width = _t.tableSave=='db'?'200px':'250px';
              var html = '<mc-new-vxe-table-column width="'+width+'" title="操作" :mc-tmp-data="{\'stage\':\'db\',\'apiUuid\':\'\',\'tableUuid\':\'\'}" :mc-col-config="{\'type\':\'user\',\'options\':[],\'api\':{\'method\':\'post\',\'url\':\'\',\'params\':[],\'fields\':[]}}">' +
              '<template #row="scope">' +
              '<div class="mc-div-pane">' +
              (_t.tableSave=='db'?'<el-button type="text" icon="fa fa-edit" @click="scope.vue.editEvent(scope.row)">编辑</el-button>':'' )+
              (_t.tableSave=='db'?'<el-button type="text" icon="fa fa-trash-o" @click="scope.vue.dbDelete({data:scope.row,index:scope.rowIndex,confirm:true,callback:function(data){}})">删除</el-button>':'' )+
              (_t.tableSave=='batch'?'<el-button type="text" icon="fa fa-trash-o" @click="scope.vue.apiDeleteRow({index:scope.rowIndex,pk:\''+pk.name+'\'})">删除行</el-button>':'' )+
              (_t.tableSave=='batch'?'<el-button type="text" icon="fa fa-trash-o" @click="scope.vue.apiDuplicateRow({data:scope.row,index:scope.rowIndex+1,ignores:[\''+pk.name+'\']})">复制行</el-button>':'') +
              (_t.tableSave=='batch'?'<el-button type="text" icon="fa fa-trash-o" @click="scope.vue.apiAddRow({data:{},index:scope.rowIndex})">向上加</el-button>':'' )+
              (_t.tableSave=='batch'?'<el-button type="text" icon="fa fa-trash-o" @click="scope.vue.apiAddRow({data:{},index:scope.rowIndex+1})">向下加</el-button>':'' )+
              '</div>' +
              '</template>' +
              '</mc-new-vxe-table-column>'
              return html;
            },


            fieldsKey:function (fileds) {
              var key = [];
              if(fileds){
                for(var i=0;i<fileds.length;i++){
                  key.push(fileds[i].name);
                }
              }
              return key.join(",");
            },
            //表单编辑区域
            buildEditFormHtml:function (tableRootNode) {
              var elForm = null;
              var oldFormItems = [];
              var oldFormItemMap = {};
              var html2Coder = new Html2Coder();
              var children = this.getOperateFocusNodeChildren();
              if(children){
                for(var i=0;i<children.length;i++){
                  var child =children[i];
                  if(child.magicalCoder.identifier=='template' && child.attributes['#form']){//表单
                    elForm = child.magicalCoder.children[0];
                    if(elForm){
                      var elFormItems = elForm.magicalCoder.children;
                      if(elFormItems&&elFormItems.length>0){
                        for(var j=0;j<elFormItems.length;j++){
                          var fields = html2Coder.formItemFieldNames(elFormItems[j]);
                          var key = this.fieldsKey(fields);
                          if(key){//这里的v-model会带上scope.row.
                            oldFormItemMap[key]=true;
                          }
                          oldFormItems.push(elFormItems[j]);
                        }
                      }
                    }
                  }
                }
              }
              {
                var newChildren = tableRootNode.magicalCoder.children;
                for(var i=0;i<newChildren.length;i++){
                  var formItem = newChildren[i];
                  var fields = html2Coder.formItemFieldNames(formItem);
                  var key = this.fieldsKey(fields);
                  if(key && !oldFormItemMap[key]){//说明是新增的字段
                    oldFormItems.push(formItem)
                  }
                }
              }
              var elRow = MAGICAL_CODER_API.htmlToRootNode({html:`<el-row :gutter="10" type="flex" style="flex-wrap: wrap"></el-row>`,pure:true})
              if(elForm&&this.isMergeNewField()){
                //拷贝一个旧的 然后重置内部formItem
                var copyElForm = CommonUtil.KCVUtil.cloneDeep(elForm);
                var oldColFormItems=[]
                if(this.mcGrid){
                  oldFormItems.forEach(formItem=>{
                    formItem.attributes.style="width:100%"
                    let elCol= MAGICAL_CODER_API.htmlToRootNode({html:`<el-col :xs="24" :md="${this.gridSpan}"></el-col>`,pure:true})
                    elCol.magicalCoder.children=[formItem];
                    oldColFormItems.push(elCol)
                  })
                  elRow.magicalCoder.children = oldColFormItems;
                }
                copyElForm.magicalCoder.children = this.mcGrid? [elRow]:oldFormItems;
                var html=MAGICAL_CODER_API.nodeToHtml({node:copyElForm,pure:true});
                return html
              }else {
                //用新的表单
                return MAGICAL_CODER_API.nodeToHtml({node:tableRootNode,pure:true});
              }
            },
            buildLeftQueryHtml:function (result,vifPkHtml) {
              var oldElCards = [];
              var oldElTreeMap = {};
              var insertDataParam = [];
              var children = this.getOperateFocusNodeChildren();
              if(children){
                for(var i=0;i<children.length;i++){
                  var child =children[i];
                  if(child.magicalCoder.identifier=='template' && child.attributes['#query-left']){//表单
                    var elCards = child.magicalCoder.children;
                    if(elCards&&elCards.length>0) {
                      for (var j = 0; j < elCards.length; j++) {
                        var elCard = elCards[j];
                        if (elCard.magicalCoder.children.length > 0) {
                          var elTree = elCard.magicalCoder.children[0];
                          var vmodel = elTree.attributes['v-model'];
                          if (vmodel) {
                            oldElTreeMap[vmodel] = true;
                            var field = vmodel.replace("scope.row.","")
                            insertDataParam.push(field+":scope.vue.getQuery()."+field);
                          }
                        }
                        oldElCards.push(elCard);
                      }
                    }
                  }
                }
              }
              if(!this.isMergeNewField()){
                oldElTreeMap={};
                insertDataParam=[];
                oldElCards=[];
              }

              if(result.treeNodes.length>0 && this.tableLayout=='lr')
              {
                var nodes = result.treeNodes;
                for(var i=0;i<nodes.length;i++){
                  var info = nodes[i].info;
                  var elCard = MAGICAL_CODER_API.htmlToRootNode({html:"<el-card "+vifPkHtml+" header='"+info.label+"'></el-card>"})
                  var elTreeNode = nodes[i].node;
                  var vmodel = elTreeNode.attributes['v-model'];
                  if(vmodel){
                    if(!oldElTreeMap[vmodel]){
                      elCard.magicalCoder.children = [elTreeNode];
                      oldElCards.push(elCard);
                      insertDataParam.push(info.field+":scope.vue.getQuery()."+info.field);
                    }
                  }
                }
              }
              var html = MAGICAL_CODER_API.nodesToHtml({nodes:oldElCards,pure:true})
              return {html:html,insertDataParam:insertDataParam}
            },
            buildQueryHtml:function (tableRootNode,vifPkHtml,pk) {
              var elCard = null;
              var elForm = null;
              var oldFormItems = [];
              var oldFormItemMap = {};
              var html2Coder = new Html2Coder();
              var children = this.getOperateFocusNodeChildren();
              var queryBtn= MAGICAL_CODER_API.htmlToRootNode({
                html:'<el-button '+vifPkHtml+' @click="scope.vue.queryTable" type="primary" size="small">查询</el-button>',
                pure:true
              })
                var resetBtn=MAGICAL_CODER_API.htmlToRootNode({
                    html:' <el-button '+vifPkHtml+'  @click="scope.vue.resetQueryData" size="small">重置</el-button>',
                    pure:true
                  })
              if(children){
                for(var i=0;i<children.length;i++){
                  var child =children[i];
                  if(child.magicalCoder.identifier=='template' && child.attributes['#query']){//表单
                    elCard = child.magicalCoder.children[0];
                    if(elCard){
                      elForm = elCard.magicalCoder.children[0];
                      if(elForm){
                        //  判断是否有查询按钮了
                        if(!MAGICAL_CODER_API.searchNodes({
                          fromNode:elForm,
                          query:{tagName:'el-button'}
                        }).length){
                          elForm.magicalCoder.children.push(queryBtn)
                          elForm.magicalCoder.children.push(resetBtn)
                        }
                        var elFormItems = elForm.magicalCoder.children;
                        if(elFormItems&&elFormItems.length>0){
                          for(var j=0;j<elFormItems.length;j++){
                            var fields = html2Coder.formItemFieldNames(elFormItems[j]);
                            var key = this.fieldsKey(fields);
                            if(key && pk && pk.name && key=="scope.row."+pk.name){//主键就不要放查询区域了
                              continue;
                            }
                            if(key){//这里的v-model会带上scope.row.
                              oldFormItemMap[key]=true;
                            }

                            oldFormItems.push(elFormItems[j]);
                          }
                        }
                      }
                    }
                  }
                }
              }
              {
                var newChildren = tableRootNode.magicalCoder.children;
                for(var i=0;i<newChildren.length;i++){
                  var formItem = newChildren[i];
                  var fields = html2Coder.formItemFieldNames(formItem);
                  var key = this.fieldsKey(fields);
                  if(key && pk && pk.name && key=="scope.row."+pk.name){//主键就不要放查询区域了
                    continue;
                  }
                  if(key && !oldFormItemMap[key]){//说明是新增的字段
                    oldFormItems.push(formItem)
                  }
                }
              }
              if(elCard && this.isMergeNewField()){
                //拷贝一个旧的 然后重置内部formItem
                var elCard = CommonUtil.KCVUtil.cloneDeep(elCard);
                if(elCard.magicalCoder.length>0){
                  var elForm = elCard.magicalCoder.children[0];
                  elForm.magicalCoder.children = oldFormItems;
                }
                return MAGICAL_CODER_API.nodeToHtml({node:elCard,pure:true});
              }else {
                tableRootNode.magicalCoder.children.push(queryBtn)
                tableRootNode.magicalCoder.children.push(resetBtn)
                return "<el-card class='xlyk-el-card' "+vifPkHtml+">"+MAGICAL_CODER_API.nodeToHtml({node:tableRootNode,pure:true})+"</el-card>";
              }
            },
            //操作区域按钮
            buildTableToolbarHtml:function (pk,vifPkHtml,insertDataParam,tableName,suffix) {
              var elCol = null;
              var children = focusNode.magicalCoder.children;
              if(children){
                for(var i=0;i<children.length;i++){
                  var child =children[i];
                  if(child.magicalCoder.identifier=='template'
                    && child.attributes['#operate']
                    &&child.magicalCoder.children.length>0){
                    elCol = child.magicalCoder.children[0];
                  }
                }
              }
              if(this.operate=='parent'&&elCol && this.isMergeNewField()){//不用改用户的默认配置
                return MAGICAL_CODER_API.nodeToHtml({node:elCol,pure:true});
              }

              var _t = this;
              var html = '<el-col :span="24"><vxe-toolbar class="mc-on-shade" '+(this.operate=='parent'?'custom print':'')+'><template #buttons><el-col :span="24">' +
              // '<el-button '+vifPkHtml+' @click="scope.vue.queryTable" size="small">查询</el-button><el-button '+vifPkHtml+'  @click="scope.vue.resetQueryData" size="small">重置</el-button>'+
              (_t.tableSave=='db'?'<el-button  @click="scope.vue.insertData({form:{'+insertDataParam.join(",")+'}})" size="small" type="primary">新增</el-button>':'') +
               (_t.tableSave=='db'?'<el-button @click="scope.vue.dbSave({data:{'+insertDataParam.join(",")+'},confirm:true,callback:function(data){scope.vue.apiAddRow({data:{'+insertDataParam.join(",")+(insertDataParam.length>0?",":"")+pk.name+':data.res.data}})}})" size="small" type="primary">添加行</el-button>':'')+
               (_t.tableSave=='batch'?'<el-button @click="scope.vue.apiAddRow({data:{'+insertDataParam.join(",")+'}})" size="small" type="primary">新增行</el-button>':'')+
              '<el-button '+vifPkHtml+'  @click="scope.vue.printTable(\'all\')" size="small" type="primary">打印全部</el-button><el-button '+vifPkHtml+' @click="scope.vue.printTable(\'checked\')" size="small" type="primary">打印勾选</el-button>' +
              '<el-button '+vifPkHtml+' @click="scope.vue.exportExcel(\'page\')" size="small" type="primary">导出当前页Excel</el-button><el-button '+vifPkHtml+' @click="scope.vue.exportExcel(\'all\')" size="small" type="primary">导出Excel</el-button>' +
              '<mc-image-upload '+vifPkHtml+' :mc-show-upload-icon="false" :show-file-list="false"  name="file" style="display: inline-block" action="magical_lowcode/openapi/crud/'+tableName+'/import-excel'+suffix+'"><el-button size="small" type="warning">上传Excel</el-button></mc-image-upload>' +
              // '<el-button '+vifPkHtml+' @click="scope.vue.exportTable(\'all\')" size="small" type="primary">导出CSV</el-button><el-button '+vifPkHtml+' @click="scope.vue.exportTable(\'checked\')" size="small" type="primary">导出勾选CSV</el-button>' +
              '</el-col></template></vxe-toolbar></el-col>';
              return html;
            },
            //弹窗区域底部操作按钮
            buildDialogToolHtml:function () {
              var mcSpanPane = null;
              var children = focusNode.magicalCoder.children;
              if(children){
                for(var i=0;i<children.length;i++){
                  var child =children[i];
                  if(child.magicalCoder.identifier=='template'
                    && child.attributes['#dialog-footer']
                    &&child.magicalCoder.children.length>0){//表单
                     mcSpanPane = child.magicalCoder.children[0];
                  }
                }
              }
              if(mcSpanPane && this.isMergeNewField()){//不用改用户的默认配置
                return MAGICAL_CODER_API.nodeToHtml({node:mcSpanPane,pure:true});
              }
              return "<span class=\"mc-span-pane\"><el-button size=\"small\" @click=\"scope.vue.closeDialog\">取消</el-button>" +
                "<el-button size=\"small\" type=\"primary\" @click=\"scope.vue.submitForm()\" :icon=\"scope.loading.save?'el-icon-loading':''\" :disabled=\"scope.loading.save\">确定</el-button></span>";//默认
            },
            tableFields:function(rootNode){
              var tableInfo = {};
              //字段信息
              var tableFields = [];//{name:"",type:"",len:2,defaultValue:"",pk:false,notNull:true,autoInc:false,comment:""}
              var children = rootNode.magicalCoder.children;
              if(children){
                for(var i=0;i<children.length;i++){
                  var field = {};
                  var fieldParent = null;
                  var elFormItem = children[i];
                  var attributes = elFormItem.attributes;
                  var magicalCoder = elFormItem.magicalCoder;
                  if(magicalCoder.tagName !== 'el-form-item'){
                    layer.alert("检测到存在控件不在标题控件内，请放入标题控件后再尝试");
                    return null;
                  }
                  //注释
                  field.comment = attributes.label;
                  {//寻找包含的控件
                    if(magicalCoder.children){
                      var controlNode = magicalCoder.children[0]
                      var controlAttributes = controlNode.attributes;
                      var vModel = controlAttributes['v-model'];
                      field.name = vModel;
                      if(!vModel){
                        field.name = controlAttributes[':data.sync'];//其他自定义的组件 暂时取这个名字
                      }
                    }
                  }
                  tableFields.push(field);
                }
              }
              tableInfo.fields = tableFields;
              return tableInfo;
            },
            buildColConfigHtml:function(controlNode){
              var config = ""
              var tagName = controlNode.magicalCoder.tagName;
              switch(tagName){
                case 'mc-checkbox-group':
                  config = {type:'checkbox',options:[]}
                  var cbxChildren = controlNode.magicalCoder.children;
                  for(var i=0;i<cbxChildren.length;i++){
                    var cbx = cbxChildren[i];
                    if(cbx.magicalCoder.children &&cbx.magicalCoder.children.length>0){
                      var k = cbx.attributes['label'];
                      var v = cbx.magicalCoder.children[0].magicalCoder.textContent;
                      config.options.push({k:k,v:v});
                    }
                  }
                  break;
                case 'el-radio-group':
                  config = {type:'radio',options:[]}
                  var rdiChildren = controlNode.magicalCoder.children;
                  for(var i=0;i<rdiChildren.length;i++){
                    var rdi = rdiChildren[i];
                    if(rdi.magicalCoder.children &&rdi.magicalCoder.children.length>0){
                      var k = rdi.attributes['label'];
                      var v = rdi.magicalCoder.children[0].magicalCoder.textContent;
                      config.options.push({k:k,v:v});
                    }
                  }
                  break;
                case 'el-select':
                  config = {type:'select',options:[]}
                  var options = controlNode.magicalCoder.children;
                  for(var i=0;i<options.length;i++){
                    var option = options[i];
                    var v = option.attributes['label'];
                    var k = option.attributes['value'];
                    config.options.push({k:k,v:v});
                  }
                  break;
                case 'mc-switch':
                  config = {type:'boolean',options:[]}
                  var activeText = controlNode.attributes['active-text'] || "是"
                  var inActiveText = controlNode.attributes['inactive-text'] || "否"
                  config.options.push({k:"true",v:activeText})
                  config.options.push({k:"false",v:inActiveText})
                  break;
                case 'mc-remote-select':
                  var mcColConfig = controlNode.attributes[':mc-config'];//把limit替换掉
                  if(mcColConfig){
                    mcColConfig = JSON.parse(mcColConfig.replace(/'/g,'"'));
                    delete mcColConfig.api['limit'];
                    mcColConfig = JSON.stringify(mcColConfig).replace(/"/g,'\'')
                    var mcTmpData = controlNode.attributes[':mc-config-tmp']
                    return ' :mc-col-config="'+mcColConfig+'" :mc-tmp-data="'+mcTmpData+'"';
                  }
                  break;
                case 'mc-select':
                  config = controlNode.attributes[':mc-config'];
                  if(config){
                    return ' :mc-col-config="'+config+'"';
                  }
                  break;
                case 'mc-tree':
                  var elInput = MAGICAL_CODER_API.searchNodes({fromNode:controlNode,query:{tagName:"el-input"}});
                  var pkTextField = "";
                  if(elInput){
                    var vModel = elInput[0].attributes['v-model'];
                    if(vModel){
                      var arr = vModel.split(".");
                      pkTextField = arr[arr.length-1];
                    }
                  }
                {
                  var config = controlNode.attributes[':mc-config'];
                  if(config){
                    config = JSON.parse(config.replace(/'/g,'\"'));
                    var nodeKey = config.nodeKey;
                    delete  config.nodeKey;
                    delete  config.mcNodeParentKey;
                    delete config.api['limit'];
                    config.pkField = nodeKey;
                    config.pkTextField = pkTextField;
                    config.type='pk';
                    config.options=[];
                    var mcTmpData = controlNode.attributes[':mc-config-tmp']
                    return ' :mc-col-config="'+JSON.stringify(config).replace(/"/g,'\'')+'" :mc-tmp-data="'+mcTmpData+'"';
                  }
                }
                  break;
              }
              if(config){
                return ' :mc-col-config="'+JSON.stringify(config).replace(/"/g,'\'')+'"';
              }
              return "";
            },
            parsePCSConfig:function(mcChildColConfig){
              if(mcChildColConfig){
                mcChildColConfig = JSON.parse(mcChildColConfig.replace(/'/g,'"'));
                delete mcChildColConfig.api['limit'];
                mcChildColConfig.type = "pk";
                var tmp = mcChildColConfig.tmp;
                delete mcChildColConfig['tmp'];
                mcChildColConfig = JSON.stringify(mcChildColConfig).replace(/"/g,'\'');
                var mcTmpData = JSON.stringify(tmp).replace(/"/g,'\'');
                return ' :mc-col-config="'+mcChildColConfig+'" :mc-tmp-data="'+mcTmpData+'"' ;
              }
              return "";
            },
            htmlUtil:function () {
              var _t = this;
              var util = {
                mcElTabs:function (elTabPane) {
                  var uuid = CommonUtil.KCVUtil.pubGenerateClearUUID();
                  return '<mc-el-tabs id="'+uuid+'" v-model="'+uuid+'">'+elTabPane+'</mc-el-tabs>';
                },
                elTabPane:function (name,label,innerHtml) {
                  name = name||CommonUtil.KCVUtil.pubGenerateClearUUID();
                  label = label||"子表";
                  return '<el-tab-pane name="'+name+'" label="'+label+'" :lazy="MC.isPublish()?false:true">'+innerHtml+'</el-tab-pane>';
                },
                table:function () {
                  var mcOpenPane = ':mc-open-pane="{\'type\':\'drawer\',\'width\':\'70%\',\'modal\':true,\'closeOnClickModal\':true}"'
                  if(_t.isOperateChild()){//内部子表不要弹出黑窗口
                    mcOpenPane = ':mc-open-pane="{\'type\':\'drawer\',\'width\':\'70%\',\'modal\':false,\'closeOnClickModal\':true}"'
                  }
                  return '<mc-new-vxe-table  mc-version="v2" :auto-resize="true" height="600" :mc-page-size="10"   mc-query-method="post" '+mcOpenPane+'  :mc-array-fields="[]"></mc-new-vxe-table>'
                }
              }
              return util;
            },
            copyAttributes:function (node) {
              for(var key in this.attributes){
                node.attributes[key]=this.attributes[key];
              }
            },
            buildTableHtml:function () {
              var htmlUtil = this.htmlUtil();
              var tableNode = MAGICAL_CODER_API.htmlToRootNode({html:htmlUtil.table(),pure:true});
              this.copyAttributes(tableNode);

              tableNode.attributes[':data.sync']="scope.row._"+this.tableInfo.table+"_save_list"
              tableNode.attributes[':api-delete-data.sync']="scope.row._"+this.tableInfo.table+"_delete_list"
              //自身配置
              tableNode.attributes[':mc-fk']=CommonUtil.KCVUtil.objToJsonAttr(this.tableInfo);
              //传给父亲用
              tableNode.attributes[':mc-fk-value.sync']="scope.row._"+this.tableInfo.table+"_info"
              //还差一个外键查询
              tableNode.attributes['mck1']=this.tableInfo.pidName;
              tableNode.attributes['mcc1']="=";
              tableNode.attributes[':mcv1']="scope.row."+this.parentInfo.pk.name;
              //父亲scope
              tableNode.attributes[':mc-parent-scope']="scope";
              //不要显示弹窗按钮
              tableNode.attributes[':mc-dialog-footer-btn']="false";

              //新增不进行查询
              if(this.parentInfo.pk){
                tableNode.attributes[':mc-mount-query']="scope.row."+this.parentInfo.pk.name+"!=null"
              }
              MAGICAL_CODER_API.resetHtml({parentNode:tableNode,html:this.html,triggerChange:false});
              var tableHtml = MAGICAL_CODER_API.nodeToHtml({node:tableNode,pure:true})
              return tableHtml;
            },
            vIfParentPkNotNullHtml:function () {
              //在设计器里不要隐藏
              return this.operate=='child'?" v-if='MC.dev.design()||scope.parent.row."+this.parentInfo.pk.name+"!=null' ":"";
            },
            isOperateChild:function () {
              return this.operate=='child';
            },
            submitForm:function () {
              if(!this.tableInfo.table){
                this.$message({type:"warning",message:"请先选择表"});
                return;
              }
              if(this.operate=='parent'){//父表配置
                for(var key in this.attributes){
                  focusNode.attributes[key]=this.attributes[key];
                }
                MAGICAL_CODER_API.resetHtml({parentNode:focusNode,html:this.html,triggerChange:true});
              }else {//子表配置
                if(!this.parentInfo || !this.parentInfo.pk){
                  this.$message({type:"error",message:"操作失败：检测到数据仓库中子表缺少父表外键下拉框配置,无法为您自动绑定"});
                  return;
                }
                this.changeParent(focusNode);
                this.appendChild(focusNode);
              }
              this.drawer = false;
            },
            appendChild:function (focusNode) {
              if(focusNode.magicalCoder.identifier=='mc-new-vxe-table'){
                var formTemplate = MAGICAL_CODER_API.searchNodes({fromNode:focusNode,query:{identifier:"template"},attributes:['#form==scope']})
                if(formTemplate.length>0){
                  var form = formTemplate[0].magicalCoder.children[0];
                  var htmlUtil = this.htmlUtil();
                  //查找tabs
                  var elTabs = MAGICAL_CODER_API.searchNodes({fromNode:form,query:{identifier:"mc-el-tabs"},limit:1});
                  var tableHtml = this.buildTableHtml();
                  if(!tableHtml){
                    return;
                  }
                  if(elTabs.length>0){
                    var elTab = elTabs[0];
                    //找一下有没有tab的first配置
                    var children = elTab.magicalCoder.children;
                    var existFirst = false;
                    for(var i=0;i<children.length;i++){
                      var name = children[i].attributes['name'];
                      if(name =='first'){
                        existFirst=true;
                        break
                      }
                    }
                    if(existFirst==false&&children.length>0){
                      children[0].attributes.name='first';
                    }
                    var elTabPaneHtml = htmlUtil.elTabPane("",this.tableInfo.table,tableHtml);
                    MAGICAL_CODER_API.appendHtml({parentNode:elTab,html:elTabPaneHtml,triggerChange:true})

                  }else {//当前是第一个 构造一个
                    var elTabsHtml = htmlUtil.mcElTabs(htmlUtil.elTabPane("first",this.tableInfo.table,tableHtml))
                    //找最后一个
                    MAGICAL_CODER_API.appendHtml({parentNode:form,html:'<el-form-item label-width="0px">'+elTabsHtml+'</el-form-item>',triggerChange:true})
                  }
                }
                this.$message({type:"success",message:"请打开编辑页查看"})
              }
            },
            changeParent:function (focusNode) {
              if(this.cascadeDelete){//级联删除
                //查找父亲配置的外键
                var parentCascadeConfig = CommonUtil.KCVUtil.jsonAttrToObj(focusNode.attributes[':mc-cascade']);
                var _children = parentCascadeConfig['_children'] ||[];
                var exist = false;
                for(var i=0;i<_children.length;i++){
                  var child = _children[i]['_info'];
                  if(child.catalog==this.tableInfo.catalog && child.schema==this.tableInfo.schema && child.table==this.tableInfo.table){
                    child.pidName = this.tableInfo.pidName;
                    exist = true;
                  }
                }
                if(!exist){
                  _children.push({_info:this.tableInfo});
                }
                parentCascadeConfig['_children']=_children;
                focusNode.attributes[':mc-cascade']=CommonUtil.KCVUtil.objToJsonAttr(parentCascadeConfig);
              }
            }
          }
        })
      }
    }
  }
  return config;
}
//上下结构子表
McNewVxeTableConfig.prototype.upDownChildrenConfig=function () {
  var _tt = this;
    var config = {type:"html",
      callback:{
        htmlCallback:function(param){
          var htmlTemp = '<div class="layui-row layui-col-space3" id="mcChildrenApp">'+
            '<div class="layui-col-xs12 mc-change-attr__now__box mc-api-reset">'+
            '<mc-api :data="mcConfig"  label-position="top"  :fields="fields" :show-url="false"  :show-save-btn="false" :show-fields="false" :show-limit="false"></mc-api>'+
            '</div>'+
            '<div class="layui-col-xs6 mc-change-attr__now">上下布局子表</div>'+
            '<div class="layui-col-xs6">'+
            '<el-button size="mini" type="primary" @click="addChildren">添加子表</el-button>'+
            '</div>'+
            '</div>';
          return htmlTemp;
        },
        render:function (param) {
          //从magicalCoder获取当前聚焦节点的属性值 准备传入vue里
          var focusNode=param.focusNode;
          var  mcConfig = {'params':[],'fields':[]}
          var params = CommonUtil.KCVUtil.getParams(focusNode);
          mcConfig.params = params;
          var config = CommonUtil.KCVUtil.jsonAttrToObj(focusNode.attributes[":mc-config"],{api:{orders:[]}});
          mcConfig.orders = config.api.orders;
          new Vue({
            el: '#mcChildrenApp',
            data: {
              mcConfig:mcConfig,
              fields:[]
            },
            mounted:function(){

            },
            watch:{
              mcConfig:{
                handler:function(nv){
                  if(this.mcConfig.orders){
                    var check = true;
                    for(var i=0;i<this.mcConfig.orders.length;i++){
                      if(this.mcConfig.orders[i].name && this.mcConfig.orders[i].type){

                      }else {
                        check = false;
                        break;
                      }
                    }
                    if(check){
                      MAGICAL_CODER_API.changeAttr({node:focusNode,name:":mc-config",value:CommonUtil.KCVUtil.objToJsonAttr({api:{orders:this.mcConfig.orders}}),triggerChange:false})
                    }
                  }
                  CommonUtil.KCVUtil.toParams(focusNode,this.mcConfig.params,'',false);

                },
                deep:true
              }
            },
            methods:{
              buildChildTableHtml:function(){
                return _tt.TABLE_HTML.replace('<mc-new-vxe-table ','<mc-new-vxe-table :auto-resize="true" :mc-from-parent-query="scope.parent" :mc-pid-field-map="{\'pid\':\'id\'}" ');
              },
              addChildren:function(){
                var children = focusNode.magicalCoder.children;
                for(var i=0;i<children.length;i++){
                  var child = children[i];
                  var slotParent = child.attributes['#parent'];
                  if(slotParent){//找到了 加个lazy有利于内部空间宽自适应
                    if(child.magicalCoder.children.length<=0){
                      var html = '<el-tabs @tab-click="tabClick"><el-tab-pane  :lazy="true" name="first" label="子表">'+this.buildChildTableHtml()+'</el-tab-pane></el-tabs>';
                      MAGICAL_CODER_API.resetHtml({parentNode:child,html:html,triggerChange:true})
                    }else{
                      var tabs = child.magicalCoder.children[0];
                      if(tabs.magicalCoder.tagName=='el-tabs'){
                        var html = '<el-tab-pane  :lazy="true" label="新子表">'+this.buildChildTableHtml()+'</el-tab-pane>';
                        MAGICAL_CODER_API.appendHtml({parentNode:tabs,html:html,triggerChange:true})
                      }else{
                        this.$notify("检测到您修改了子表的标签根节点，请自行添加吧")
                      }
                    }
                  }
                }
              }
            }
          })
        }
      }
    }
    return config;
}
McNewVxeTableConfig.prototype.apiCreateConfig=function () {
  var config = {type:"html",hide:false,
      callback:{
        htmlCallback:function(param){
          var htmlTemp =
            '<div class="layui-row layui-col-space3" id="mcApiApp">'+
            '<div class="layui-col-xs3 mc-change-attr__now">智能接口</div>'+
            '<div class="layui-col-xs9">'+
            '<el-tag effect="plain" @click="openDrawer">快速配置</el-tag>'+
            '<el-drawer @closed="closeDrawer" style="overflow-y:scroll" title="API" :visible.sync="apiDrawer" direction="rtl" :modal="false" size="500px">'+
            '<el-collapse v-model="stage" accordion>'+
            '<el-collapse-item name="saveParentChildren" title="父子表保存接口"><el-input rows="5" type="textarea" v-model="saveParentChildrenForm.script"></el-input><el-button style="margin-top:10px" type="warning" size="mini" @click="saveParentChildrenApi">保存</el-button></el-collapse-item>'+
            '</el-collapse>'+
            '</el-drawer>'+
            '</div>'+
            '</div>';
          return htmlTemp;
        },
        render:function (param) {
          //从magicalCoder获取当前聚焦节点的属性值 准备传入vue里
          var focusNode=param.focusNode;
          new Vue({
            el: '#mcApiApp',
            data: {
              apiDrawer:false,
              stage:'saveParentChildren',
              saveParentChildrenForm:{}
            },
            mounted:function(){
              this.initParentChildren();
            },
            methods:{
              openDrawer:function(){
                this.apiDrawer = true;
              },
              closeDrawer:function(){
                this.apiDrawer = false;
              },
              getTableInfoFromUrl:function(url){
                if(!url){
                  return null;
                }
                var matchSchema;
                var m = url.match(/.?magical_lowcode\/openapi\/crud\/(.*)\/.+\?catalog=(.*)&schema=(.*)/);
                if(!m){
                  m = url.match(/.?magical_lowcode\/openapi\/crud\/(.*)\/.+\?catalog=(.*)/);
                  matchSchema=false;
                }
                var tableName = "",catalog="",schema="";
                if(m){
                  tableName = m[1];
                  catalog = m[2];
                  if(matchSchema){
                    schema = m[3];
                  }
                  return {table:tableName,catalog:catalog,schema:schema}
                }
                return null;
              },
              getInfo:function(node){
                var attributes = node.attributes;
                //查找主表资料
                var urlMap = {
                  page: attributes['mc-query-url'],
                  save: attributes['mc-save-url'],
                  delete: attributes['mc-delete-url'],
                  update: attributes['mc-update-url'],
                  export: attributes['mc-export-url'],
                }
                var info = this.getTableInfoFromUrl(urlMap.page)||
                  this.getTableInfoFromUrl(urlMap.save)||
                  this.getTableInfoFromUrl(urlMap.delete)||
                  this.getTableInfoFromUrl(urlMap.update)||
                  this.getTableInfoFromUrl(urlMap.export)
                var _info = {catalog:"",schema:"",table:""}
                return $.extend(_info,info||{});
              },
              getVariableName:function(name){
                if(!name){
                  return name;
                }
                var arr = name.split(".");
                return arr[arr.length-1];
              },
              initParentChildren:function(){
                var parentInfo = this.getInfo(focusNode);
                //子表
                var templates = MAGICAL_CODER_API.searchNodes({fromNode:focusNode,query:{identifier:"template"}})
                //查找template #form="scope"
                var childrenCode = [];
                var childNames = []
                for(var i=0;i<templates.length;i++){
                  var template = templates[i];
                  if(template.attributes['#form']){
                    var children = MAGICAL_CODER_API.searchNodes({fromNode:template,query:{identifier:"mc-new-vxe-table"}});
                    if(children){
                      for(var j=0;j<children.length;j++){
                        var child = children[j];
                        var _info = this.getInfo(child);
                        //变量名
                        var saveList = this.getVariableName(child.attributes[':data.sync']);
                        var deleteList = this.getVariableName(child.attributes[':api-delete-data.sync']);
                        var code = '{saveList:'+(saveList?"body."+saveList:"null")+',deleteList:'+(deleteList?"body."+deleteList:"null")+',_info:{catalog:"'+_info.catalog+'",schema:"'+_info.schema+'",table:"'+_info.table+'",pidName:"把我改成父表字段变量名"}}';
                        childrenCode.push(code);
                        childNames.push(_info.table);
                      }
                    }
                  }
                }
                var script =
                  'body._info = {catalog:"'+parentInfo.catalog+'",schema:"'+parentInfo.schema+'",table:"'+parentInfo.table+'"};\n'+
                  'body._children = ['+childrenCode.join(",")+'];\n'+
                  'jpa.saveParentChildren(body);\n'
                var name = "save-"+parentInfo.table+"-"+childNames.join("-")
                this.saveParentChildrenForm={
                  projectId:projectUuid,
                  path:"/"+name,
                  method:"POST",
                  name:name,
                  script:script
                }

              },
              saveParentChildrenApi:function(){
                if(this.saveParentChildrenForm.script.indexOf("pidName:\"把我改成父表字段变量名\"")!=-1){
                  this.$message({type:"error",message:"失败：检测到您未填写pidName的值,该值为子表配置的【父表的变量名】"});
                  return;
                }
                var _t= this;
                CommonUtil.axiosWithServerName("post","/api/auto-save-api",
                  this.saveParentChildrenForm,function(response){
                    MAGICAL_CODER_API.changeAttr({node:focusNode,name:"mc-save-url",value:response.data.fullpath,triggerChange:true})
                    _t.$message({type:"success",message:"保存成功"})
                  }
                )
              }
            }
          })
        }
      }
    }
  return config;
}
window.McNewVxeTableConfig = new McNewVxeTableConfig();
